package com.cosmoplat.xikai.business.modbus.utils;

import com.cosmoplat.xikai.business.modbus.listerner.BasicProcessImageListener;
import com.serotonin.modbus4j.BasicProcessImage;
import com.serotonin.modbus4j.ModbusSlaveSet;
import com.serotonin.modbus4j.ip.tcp.TcpSlave;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhangyanda
 */
@Slf4j
@Component
public class Modbus4jUtils {
    private static ModbusSlaveSet salve;
    private static BasicProcessImageListener basicProcessImageListener;
    @Autowired
    public void setBasicProcessImageListener(BasicProcessImageListener basicProcessImageListener) {
        Modbus4jUtils.basicProcessImageListener = basicProcessImageListener;
    }
    /**
     * 创建从站
     *
     * @param port
     * @param slaveId
     */
    public static void createSalve(Integer port, Integer slaveId) {
        salve = new TcpSlave(port, false);
        /* 初始化过程影像区 */
        BasicProcessImage processImage = new BasicProcessImage(slaveId);
        processImage.setInvalidAddressValue(Short.MIN_VALUE);
        /* 初始化过程影像区各个数值为0 */
        for (int i = 0; i < 608; i++) {
            processImage.setHoldingRegister(i, (short) 0);
        }
        /* 为影像区添加监听 */
        processImage.addListener(basicProcessImageListener);
        //向过程影像区添加数据
        salve.addProcessImage(processImage);

        //获取寄存器
        salve.getProcessImage(slaveId);
        try {
            salve.start();
        } catch (Exception e) {
            log.error("启动从站异常:{}", e);
        }
    }

    /**
     * 修改从站地址
     *
     * @param slave
     * @param offset
     * @param newValue
     */
    public static void setRegisterValue(int slave, int offset, short newValue) {
        log.info("进入方法");
        if (salve != null) {
            BasicProcessImage processImage = (BasicProcessImage) salve.getProcessImage(slave);
            if (processImage != null) {
                processImage.setHoldingRegister(offset, newValue);
                log.info("成功将寄存器 " + offset + " 设置为 " + newValue);
            } else {
                log.info("未能找到指定的过程影像");
            }
        } else {
            log.info("Modbus 从站尚未启动");
        }
    }
}
